/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.Map;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.commons.lang3.Validate;

import ru.irenproject.store.AspectId;
import ru.irenproject.store.Initializer;

import com.google.common.collect.ImmutableMap;

@Singleton public final class QuestionEditorProvider {
  private static final AspectId ASPECT_ID = new AspectId(0xd95bb5774b36141dL);

  private final ImmutableMap<Class<? extends Question>, Class<? extends AbstractQuestionEditor>> fMap;

  @Inject QuestionEditorProvider(Map<Class<? extends Question>, Class<? extends AbstractQuestionEditor>> map) {
    fMap = ImmutableMap.copyOf(map);
  }

  public AbstractQuestionEditor open(final Question question) {
    Class<? extends AbstractQuestionEditor> editorClass = fMap.get(question.getClass());
    Validate.notNull(editorClass, "No question editor for %s.", question.getClass());

    return Utils.requireAspect(question, ASPECT_ID, editorClass, new Initializer<AbstractQuestionEditor>() {
      @Override public void initialize(AbstractQuestionEditor target) {
        target.setQuestion(question);
      }
    });
  }
}
